package com.adminserver.controller;

import cn.hutool.core.util.ObjectUtil;
import com.adminserver.entity.UserEntity;
import com.adminserver.entity.UserRoleEntity;
import com.adminserver.service.UserRoleService;
import com.adminserver.service.UserService;
import com.adminserver.util.responseUtil.ResponseEnum;
import com.adminserver.util.responseUtil.ResponseUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService userRoleService;

    @GetMapping("/pullUserPage")
    public ResponseUtil pullUserPage(@RequestParam(defaultValue = "1") int current,
                                     @RequestParam(defaultValue = "100") int size) {
        Page<UserEntity> page = new Page<>(current, size);
        userService.page(page);
        List<UserEntity> records = page.getRecords();
        //records.forEach(item -> {
        //    item.setOpenid(DesensitizedUtil.desensitized(item.getOpenid(), DesensitizedUtil.DesensitizedType.PASSWORD));
        //});
        HashMap<String, Object> map = new HashMap<>();
        map.put("records", records);
        map.put("total", page.getTotal());
        return ResponseUtil.setE(ResponseEnum.OK).setData(map);
    }

    @Transactional
    @PostMapping("/delUser")
    public ResponseUtil delUser(@RequestBody UserEntity user) {
        if (ObjectUtil.isEmpty(user)) return ResponseUtil.setE(ResponseEnum.FAIL);
        try {
            userService.removeById(user.getOpenid());
            LambdaQueryWrapper<UserRoleEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserRoleEntity::getUserId, user.getOpenid());
            userRoleService.remove(lambdaQueryWrapper);
            return ResponseUtil.setE(ResponseEnum.OK);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL);
        }
    }
}
